import 'dart:math';

import 'package:binggo_bomb/commons/CardLocalStorageWidget.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class BombStartWidget extends StatefulWidget {
  final String color;
  const BombStartWidget({super.key, required this.color});

  @override
  State<BombStartWidget> createState() => _BombStartWidgetState();
}

class _BombStartWidgetState extends State<BombStartWidget> {

  /// 中奖种子
  Map<String, List> seedNums = {};

  /// 已抽中号码
  Map<String, List> winingNums = {};
  /// 已抽号码
  List<Widget> lotteryNums = [];

  late TextEditingController controller;

  @override
  void initState() {
    super.initState();
    controller = TextEditingController();
    /// 获取中奖号码
    getWinNums();

    controller.addListener(() {
      if(controller.value.text.length >= 2) {
        goNextInput();
      }
    });

  }


  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: [

          Center(
            child: Text("请输入号码", style: TextStyle(fontSize: 24),),
          ),
          SizedBox(
            height: 100,
            child: TextField(
              decoration: InputDecoration(
                border: OutlineInputBorder(),
              ),
              keyboardType: TextInputType.number,
              controller: controller,
              onSubmitted: (v) {
                print("onSubmitted");
                goNextInput();
              },
            ),
          ),

          Center(
            child: Text("已抽取号码", style: TextStyle(fontSize: 24),),
          ),
          Wrap(
            direction: Axis.horizontal,
            children: lotteryNums,
          ),

          ///
          Divider(
            color: Colors.red,
            height: 35,
          ),
          SizedBox(
            child: SingleChildScrollView (
              child: Column(children: buildWinNumsWidget(),),
            ),
          ),



          // SizedBox(
          //   // height: 200,
          //   child: ,
          // )

        ],
      ),
    );
  }


  getWinNums () {
    Map res = CardLocalStorageWidget.getCardNums(int.parse(widget.color));
    Map<String, List> cardNums = {};
    List keys = res.keys.toList();
    for(String key in keys) {
      /// 获取卡片数据
      List card = res[key];
      List cardWin = getCardWinNums(card);
      setState(() {
        cardNums[key] = cardWin;
      });
    }
    setState(() {
      seedNums = cardNums;
    });
  }


  List<Widget> buildWinNumsWidget() {
    List<Widget> list = [];
    List keys = seedNums.keys.toList();
    for(String key in keys) {
      List cards = seedNums[key] as List;
      List<Widget> cardWidget = getNumsRow(cards);
      list.addAll(cardWidget);
    }
    return list;
  }


  List<Widget> getNumsRow(List cards) {
    double _w = MediaQuery.of(context).size.width;
    double _ws = (_w - 20) / 5;
    List<Widget> list = [];
    list.add(Center(child: Text("----------卡券分割线------------"),));

    /// 数据存储区
    List<Widget> data = [];
    for(List card in cards) {
      data.add(Row(
        children: card.map((element) => Container(
            width: _ws,
            height: 25,
            color: getRandomColor(),
            alignment: Alignment.center,
            child: Text(element.toString(), style: TextStyle(fontSize: 18, color: Colors.white),),
          ),
        ).toList(),
      ));
    }
    /// 将数据存放在ListView
    list.add(Column(
      children: data,
    ));

    return list;
  }


  List getCardWinNums (List card) {
    List list = [];
    List<int> win1 = [card[0], card[1], card[2], card[3], card[4], ];
    list.add(win1);
    List<int> win2 = [card[5], card[6], card[7], card[8], card[9], ];
    list.add(win2);
    List<int> win3 = [card[10], card[11], card[12], card[13], card[14], ];
    list.add(win3);
    List<int> win4 = [card[15], card[16], card[17], card[18], card[19], ];
    list.add(win4);
    List<int> win5 = [card[20], card[21], card[22], card[23], card[24], ];
    list.add(win5);
    List<int> win6 = [card[0], card[5], card[10], card[15], card[20], ];
    list.add(win6);
    List<int> win7 = [card[1], card[6], card[11], card[16], card[21], ];
    list.add(win7);
    List<int> win8 = [card[2], card[7], card[12], card[17], card[22], ];
    list.add(win8);
    List<int> win9 = [card[3], card[8], card[13], card[18], card[23], ];
    list.add(win9);
    List<int> win10 = [card[4], card[9], card[14], card[19], card[24], ];
    list.add(win10);
    List<int> win11 = [card[0], card[6], card[12], card[18], card[24], ];
    list.add(win11);
    List<int> win12 = [card[4], card[8], card[12], card[16], card[20], ];
    list.add(win12);

    return list;
  }



  Color getRandomColor() {
    return Color.fromARGB(255, Random.secure().nextInt(200), Random.secure().nextInt(200), Random.secure().nextInt(200));
  }


  goNextInput() {
    int num = int.parse(controller.value.text);
    List keys = seedNums.keys.toList();
    bool isIn = false;
    for(String key in keys) {
      List seeds = seedNums[key] as List;
      isIn = isIncluded(num, seeds, key);
    }
    // 将号码记录到下面
    setState(() {
      lotteryNums.add(getNumWidget(num.toString(), isIn));
    });
    controller.clear();
    isWinner();
  }

  Widget getNumWidget(String num, bool isRed) {
    return Container(
      width: 25, height: 25,
      color: isRed? Colors.redAccent : Colors.black87,
      alignment: Alignment.center,
      child: Text(num, style: TextStyle(color: Colors.white),),
    );
  }

  /// 判断本次输入的数字是否在奖券中存在
  bool isIncluded (int num, List seeds, String cardKey) {
    bool _isIn = false;
    for(int i =0;i < seeds.length; i++) {
      List nums = seeds[i];
      /// 判断数字是否在奖券中
      if(nums.contains(num)) {
        _isIn = true;
        dynamic li = winingNums[cardKey + '-' + (i+1).toString()];
        if(null == li) {
          li = [];
        } else {
          li = winingNums[cardKey + '-' + (i+1).toString()] as List;
        }
        if(li.contains(num)) { // 该号码是否已重复抽取
          print("该号码是否已重复抽取");
        } else {
          li.add(num);
          winingNums[cardKey + '-' + (i+1).toString()] = li;
        }

      }
    }
    return _isIn;
  }

  /// 判断是否中奖
  bool isWinner() {
    List keys = winingNums.keys.toList();
    for(String key in keys) {
      List winCardNum = winingNums[key] as List;
      if(winCardNum.length == 5) {
        showDialog(
            context: context,
            builder: (ctx) {
              return AlertDialog(
                  title:Text("恭喜！！！！！"),
                  content: Text("您中奖拉！中奖号码是："+ winCardNum.toString()),
              );
            }
        );
        break;
      }
    }

    return false;
  }
}
